/*
 * Copyright 2020-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.oauth2.server.authorization.authentication;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.util.Assert;

import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;

/**
 * An {@link AuthenticationProvider} implementation for OAuth 2.0 Token Revocation.
 *
 * @author Vivek Babu
 * @author Joe Grandja
 * @since 0.0.3
 * @see OAuth2TokenRevocationAuthenticationToken
 * @see OAuth2AuthorizationService
 * @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-2.1">Section 2.1 Revocation Request</a>
 */
public final class OAuth2TokenRevocationAuthenticationProvider implements AuthenticationProvider {
	private final Log logger = LogFactory.getLog(getClass());
	private final OAuth2AuthorizationService authorizationService;

	/**
	 * Constructs an {@code OAuth2TokenRevocationAuthenticationProvider} using the provided parameters.
	 *
	 * @param authorizationService the authorization service
	 */
	public OAuth2TokenRevocationAuthenticationProvider(OAuth2AuthorizationService authorizationService) {
		Assert.notNull(authorizationService, "authorizationService cannot be null");
		this.authorizationService = authorizationService;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication =
				(OAuth2TokenRevocationAuthenticationToken) authentication;
		// 获取OAuth2ClientAuthenticationToken对象，并判断是否已认证 正常流程到达此处经过OAuth2ClientAuthenticationFilter此处应该是已认证状态
		OAuth2ClientAuthenticationToken clientPrincipal =
				getAuthenticatedClientElseThrowInvalidClient(tokenRevocationAuthentication);
		// 从OAuth2ClientAuthenticationToken对象中获取已认证的客户端信息，而该客户端信息是根据/oauth2/token请求中传递的clientId，clientSecret
		// 经过查询验证没问题后封装到该对象中的
		RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
		// 根据token从oauth2_authorization获取发放令牌记录信息(token生成时会往该表中存入数据) -- 相当于对token是否存在进行校验
		OAuth2Authorization authorization = this.authorizationService.findByToken(
				tokenRevocationAuthentication.getToken(), null);
		if (authorization == null) {
			if (this.logger.isTraceEnabled()) {
				this.logger.trace("Did not authenticate token revocation request since token was not found");
			}
			// Return the authentication request when token not found
			// 当未找到令牌时返回身份验证请求
			return tokenRevocationAuthentication;
		}
		// 当前请求传递的已认证的客户端信息是否是颁发token时授权的客户端信息，避免被劫持
		if (!registeredClient.getId().equals(authorization.getRegisteredClientId())) {
			throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
		}
		// 根据传递过来的token值对应的token集合，传递过来的可能是access_token或者refresh_token又或者id_token或者state等，
		// 上面查询的时候是以or的关系查询出来的，所以可能存在多个，此处根据token获取唯一
		OAuth2Authorization.Token<OAuth2Token> token = authorization.getToken(tokenRevocationAuthentication.getToken());
		// 将该token对应的metadata中的metadata.token.invalidated设置为true，意味着该token已失效，无法再使用
		authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, token.getToken());
		// 将失效信息更新到oauth2_authorization中
		this.authorizationService.save(authorization);

		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Saved authorization with revoked token");
			// This log is kept separate for consistency with other providers
			this.logger.trace("Authenticated token revocation request");
		}

		return new OAuth2TokenRevocationAuthenticationToken(token.getToken(), clientPrincipal);
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return OAuth2TokenRevocationAuthenticationToken.class.isAssignableFrom(authentication);
	}
}
